package org.me.marble;

import android.view.*;
import android.widget.*;
import android.content.*;

import android.graphics.Color;
import android.app.AlertDialog;
import android.hardware.SensorEvent;

/**
 *
 * @author tungi
 */

public class ControlSettings implements AdapterView.OnItemClickListener,
            SeekBar.OnSeekBarChangeListener,DialogInterface.OnClickListener,
            View.OnClickListener,DialogInterface.OnKeyListener,MySensorEventListener{
    private OptionsActivity _options;
    private EditText left,right;
    private MySensorEvent listener;
    private IconArrayAdapter<String> keyadapter,tiltadapter;

    private float tilt_orientation=0.0f;
    private int leftKeyCode=0,rightKeyCode=0;
    private boolean isleftselected=false,isrightselected=false,tilt_dialog=false;

    public ControlSettings(OptionsActivity _options){
        this._options=_options;
    }

    public void createView(){
        _options.setContentView(R.layout.controlsettings);

        ListView view;
        ArrayAdapter<String> adapter;
                               
        keyadapter=new IconArrayAdapter<String>(_options.getApplicationContext(),
                R.layout.iconlistitem,R.iconlistitem.icon,
                R.iconlistitem.label,new int[]{android.R.drawable.ic_menu_more},
                new String[]{"Configure Keys"},new boolean[]{true});

        view=(ListView)_options.findViewById(R.list.keys);
        view.setId(R.list.keys);
        view.setOnItemClickListener(this);

        adapter=new ArrayAdapter<String>(_options,
                android.R.layout.simple_list_item_multiple_choice,
                new String[]{"On-Screen Control","Enable Tilt Control"});
        
        view=(ListView)_options.findViewById(R.list.tiltonscreen);
        view.setAdapter(adapter);
        view.setId(R.list.tiltonscreen);
        view.setOnItemClickListener(this);
        view.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        view.setItemChecked(0,OptionsLibrary.onscreen);
        view.setItemChecked(1,OptionsLibrary.tilt_control);

        tiltadapter=new IconArrayAdapter<String>(_options.getApplicationContext(),
                R.layout.iconlistitem,R.iconlistitem.icon,
                R.iconlistitem.label,new int[]{android.R.drawable.ic_menu_more},
                new String[]{"Configure Tilt"},new boolean[]{true});
        view=(ListView)_options.findViewById(R.list.conftilt);
        view.setAdapter(adapter);
        view.setId(R.list.conftilt);
        view.setOnItemClickListener(this);

        if(OptionsLibrary.tilt_control){
            changeKeyControlState(false);
            changeTiltControlState(true);
        }
        else if(OptionsLibrary.onscreen){
        	changeKeyControlState(false);
            changeTiltControlState(false);
        }
        else{
            changeKeyControlState(true);
            changeTiltControlState(false);
        }

        SeekBar seek=(SeekBar)_options.findViewById(R.control.key);
        seek.setProgress(OptionsLibrary.key_sensitivity-1);
        seek.setOnSeekBarChangeListener(this);
        seek=(SeekBar)_options.findViewById(R.control.tilt);
        seek.setProgress(OptionsLibrary.tilt_sensitivity-1);
        seek.setOnSeekBarChangeListener(this);
    }

    public void changeKeyControlState(boolean enable){
        ListView view=(ListView)_options.findViewById(R.list.keys);
        TextView text=(TextView)_options.findViewById(R.text.keys);
        SeekBar seek=(SeekBar)_options.findViewById(R.control.key);

        view.setEnabled(enable);
        keyadapter.setEnable(0,enable);
        view.setAdapter(keyadapter);

        if(enable)
            text.setTextColor(Color.WHITE);   
        else
            text.setTextColor(Color.GRAY);
        seek.setEnabled(enable);
    }

    public void changeTiltControlState(boolean enable){
        ListView view=(ListView)_options.findViewById(R.list.conftilt);
        TextView text=(TextView)_options.findViewById(R.text.tilt);
        SeekBar seek=(SeekBar)_options.findViewById(R.control.tilt);

        view.setEnabled(enable);
        tiltadapter.setEnable(0,enable);
        view.setAdapter(tiltadapter);

        if(enable)
            text.setTextColor(Color.WHITE);
        else
            text.setTextColor(Color.GRAY);
        seek.setEnabled(enable);
    }

    public String keyCodeToString(int keyCode){
        String[] keys=_options.getResources().getStringArray(R.array.keycode_labels);
        if(keyCode>keys.length)
            return "";
        else
            return keys[keyCode-1];
    }
    
//################################ABSTACT METHODS###############################

    //for ListView
    public void onItemClick(AdapterView<?> arg0, View view, int pos, long id){
    	if(arg0.getId()==R.list.tiltonscreen && pos==0){
    		OptionsLibrary.onscreen=!OptionsLibrary.onscreen;
    		OptionsLibrary.tilt_control=false;
    		if(OptionsLibrary.onscreen){
    			changeKeyControlState(false);
                changeTiltControlState(false);
                
                ((ListView)_options.findViewById(R.list.tiltonscreen)).setItemChecked(1,false);
    		}
    		else{
    			changeKeyControlState(true);
                changeTiltControlState(false);
    		}
    	}
        if(arg0.getId()==R.list.keys){
            leftKeyCode=OptionsLibrary.left_key;
            rightKeyCode=OptionsLibrary.right_key;
            
            LayoutInflater inflater=(LayoutInflater)
                _options.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View main=inflater.inflate(R.layout.keyconfiguration,null);

            left=(EditText)main.findViewById(R.choice.left);
            left.setBackgroundColor(Color.GRAY);
            left.setText(keyCodeToString(OptionsLibrary.left_key));
            left.setOnClickListener(this);
            
            right=(EditText)main.findViewById(R.choice.right);
            right.setBackgroundColor(Color.GRAY);
            right.setText(keyCodeToString(OptionsLibrary.right_key));
            right.setOnClickListener(this);
            
            AlertDialog ad=new android.app.AlertDialog.Builder(_options)
                .setView(main)
                .setTitle("Select keys")
                .setOnKeyListener(this)
                .setPositiveButton("Save",this)
                .setNegativeButton("Cancel",this)
                .show();
            ad.getButton(AlertDialog.BUTTON_POSITIVE).setFocusable(false);
            ad.getButton(AlertDialog.BUTTON_NEGATIVE).setFocusable(false);
        }
        else if(arg0.getId()==R.list.tiltonscreen && pos==1){
            OptionsLibrary.tilt_control=!OptionsLibrary.tilt_control;
            OptionsLibrary.onscreen=false;
            if(OptionsLibrary.tilt_control){
                changeKeyControlState(false);
                changeTiltControlState(true);
                ((ListView)_options.findViewById(R.list.tiltonscreen)).setItemChecked(0,false);
            }
            else{
                changeKeyControlState(true);
                changeTiltControlState(false);
            }
        }
        else if(arg0.getId()==R.list.conftilt){
            try{
            	listener=MySensorEvent.register(_options,this);
        	}catch(Exception e){}
            if(listener!=null){
                tilt_dialog=true;
                new AlertDialog.Builder(_options)
                    .setIcon(R.drawable.tilt)
                    .setTitle("Tilt configuration")
                    .setView(_options.getAlertDialogView(
                            "Place your device into horizontal position."+'\n'
                            +"When you are ready choose accept button."))
                    .setPositiveButton("Accept",this)
                    .setNegativeButton("Cancel",this)
                    .show();
            }
            else if(listener==null){
                OptionsLibrary.tilt_control=false;
                changeKeyControlState(true);
                changeTiltControlState(false);
                ((ListView)_options.findViewById(R.list.tiltonscreen)).setItemChecked(1,false);
                new AlertDialog.Builder(_options)
                    .setTitle("Error!")
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setMessage("Cannot iniatilize the orientation sensor!")
                    .setNegativeButton("OK",this)
                    .show();
            }
        }
    }

    //for key settings alert dialog
    public void onClick(DialogInterface arg0,int arg1){
        if(tilt_dialog){
            if(arg1==DialogInterface.BUTTON_POSITIVE){
                OptionsLibrary.tilt_orientation=tilt_orientation;
                arg0.dismiss();
            }
            else
                arg0.dismiss();
            tilt_dialog=false;
            listener.unregister();
        }
        else{
            if(arg1==DialogInterface.BUTTON_POSITIVE){
                arg0.dismiss();
                //erase saved game
                if(leftKeyCode!=0){
                    OptionsLibrary.left_key=leftKeyCode;
                }
                if(rightKeyCode!=0){
                    OptionsLibrary.right_key=rightKeyCode;
                }
            }
            else if(arg1==DialogInterface.BUTTON_NEGATIVE){
                arg0.dismiss();
            }
        }
    }

    public boolean onKey(DialogInterface arg0,int keyCode,KeyEvent event){
        String pressed_key=keyCodeToString(keyCode);
        if(keyCode!=KeyEvent.KEYCODE_HOME && keyCode!=KeyEvent.KEYCODE_BACK
                && !pressed_key.equals("")){
            if(isleftselected && rightKeyCode!=keyCode){
                leftKeyCode=keyCode;
                isleftselected=false;
                left.setBackgroundColor(Color.GRAY);
                left.setText(pressed_key);
            }
            else if(isrightselected && leftKeyCode!=keyCode){
                rightKeyCode=keyCode;
                isrightselected=false;
                right.setBackgroundColor(Color.GRAY);
                right.setText(pressed_key);
            }
            return true;
        }
        else
            return false;
    }

    //for edittexts
    public void onClick(View view){
        EditText edit=(EditText)view;
        if(edit.equals(left)){
            if(isrightselected){
                isrightselected=false;
                right.setBackgroundColor(Color.GRAY);
            }
            isleftselected=true;
            left.setBackgroundColor(Color.rgb(255,165,0));
        }
        else if(edit.equals(right)){
            if(isleftselected){
                isleftselected=false;
                left.setBackgroundColor(Color.GRAY);
            }
            isrightselected=true;
            right.setBackgroundColor(Color.rgb(255,165,0));
        }
    }

    //for seekbars
    public void onProgressChanged(SeekBar arg0,int arg1,boolean arg2){
        SeekBar key=(SeekBar)_options.findViewById(R.control.key);
        SeekBar tilt=(SeekBar)_options.findViewById(R.control.tilt);
        if(arg0.equals(key))
            OptionsLibrary.key_sensitivity=arg0.getProgress()+1;
        else if(arg0.equals(tilt))
            OptionsLibrary.tilt_sensitivity=arg0.getProgress()+1;
    }

    public void onStartTrackingTouch(SeekBar arg0){
    }

    public void onStopTrackingTouch(SeekBar arg0){
    }

    public void onSensorChanged(SensorEvent event){
        tilt_orientation=event.values[1];
    }
}
